import './ShangPinImage.scss'
import { useState } from 'react'
import { useEventEmitter, useMount, useReactive } from 'ahooks'
import { Image, Upload, Button, App } from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import { CSS } from '@dnd-kit/utilities'
import { API_LIST } from '../../API/Api'
import { GetIndexedDB } from '../../Utils/IndexedDB'


import { SortDescendingOutlined, SortAscendingOutlined, CloseCircleOutlined } from '@ant-design/icons'
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import { useSortable, arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { useRequest } from 'alova/client'
import { Http } from '../../API'

const substitutionA01 = (data) => {
    return JSON.parse(JSON.stringify(data).replace(/uuid/g, 'id').replace(/webURL/g, 'url'))
}
const substitutionA02 = (data) => {
    return JSON.parse(JSON.stringify(data).replace(/id/g, 'uuid'))
}



const SortableItem = ({ id, url }) => {
    const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id })
    const style = { transform: CSS.Transform.toString(transform), transition }
    return (
        <div className='SortableItem' ref={setNodeRef} style={style} {...attributes}  {...listeners}>
            <img src={url} alt="" />
        </div>
    )
}

const ShangPinImage = ({ data, ModalEvent }) => {
    const { notification } = App.useApp()
    const [previewOpen, setPreviewOpen] = useState(false)
    const [previewImage, setPreviewImage] = useState('')
    const [TOKEN, setTOKEN] = useState()
    const [fileList, setFileList] = useState()

    const { send: DeleteImage } = useRequest(params => Http({ url: 'posBuySuppDeleteImage', params }), { immediate: false })
    const { send: UpdateImage } = useRequest(params => Http({ url: 'posBuySuppUpdateImage', params }), { immediate: false })

    const handlePreview = async (file) => {
        if (!file.url && !file.preview) file.preview = await getBase64(file.originFileObj)
        setPreviewImage(file.url || file.preview)
        setPreviewOpen(true)
    }

    const handleChange = (info) => {
        const { file, fileList } = info
        const { status, response } = file
        setFileList(fileList)
        if (status === 'removed')
            DeleteImage({ uuid: file.id })
                .then(() => {
                    ModalEvent.emit({ type: 'Refresh' })
                    notification.success({ key: 'success', message: '成功提醒', description: '图片删除成功!' })
                })
        if (status === 'done') {
            const obj = substitutionA01(response)
            const arr = JSON.parse(JSON.stringify(fileList))
            arr.splice(arr.length - 1, 1, obj)
            setFileList(arr)
            ModalEvent.emit({ type: 'Refresh' })
            notification.success({ key: 'success', message: '成功提醒', description: '图片上传成功!' })
        }

    }
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <PlusOutlined style={{ fontSize: 24 }} />
            <div style={{ marginTop: 8 }}>上传</div>
        </button>
    );

    useMount(async () => {
        setFileList(substitutionA01(data.children))
        setTOKEN(await GetIndexedDB('token'))
    })

    const sensors = useSensors(
        useSensor(PointerSensor),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        })
    )

    const handleDragEnd = (event) => {
        const { active, over } = event
        if (active.id !== over.id) {
            setFileList((items) => {
                const oldIndex = items.findIndex(v => v.id === active.id)
                const newIndex = items.findIndex(v => v.id === over.id)
                return arrayMove(items, oldIndex, newIndex)
            })
        }
    }




    const onSort = () => {
        const arr = substitutionA02(fileList)
        UpdateImage(arr).then(() => {
            ModalEvent.emit({ type: 'Refresh' })
            notification.success({ key: 'success', message: '成功提醒', description: '图片排序成功!' })
        })
    }


    if (fileList) {
        return (
            <div className='ShangPinImage'>
                <Upload
                    className='UploadBox'
                    listType="picture-card"
                    headers={{ Authorization: TOKEN }}
                    action={`${API_LIST()['posBuySuppAddImage']}`}
                    data={{ CaiLiaoYunShuUuid: data.uuid, ImageUuid: 1 }}
                    fileList={fileList}
                    onPreview={handlePreview}
                    onChange={handleChange}
                >
                    {fileList.length >= 6 ? null : uploadButton}
                </Upload>
                {fileList.length !== 0 &&
                    <div className='DndContext'>
                        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd} >
                            <SortableContext items={fileList} strategy={verticalListSortingStrategy}>
                                {fileList.map(({ id, url }, index) => <SortableItem key={index} id={id} url={url} />)}
                            </SortableContext>
                        </DndContext>
                        <Button type='primary' onClick={onSort}>保存排序</Button>
                    </div>
                }

                {previewImage && (
                    <Image
                        wrapperStyle={{ display: 'none' }}
                        preview={{
                            visible: previewOpen,
                            onVisibleChange: (visible) => setPreviewOpen(visible),
                            afterOpenChange: (visible) => !visible && setPreviewImage(''),
                        }}
                        src={previewImage}
                    />
                )}
            </div>
        );
    }
};

export default ShangPinImage;